package borge.web.teamspirit.client.page.team.panels;

import java.util.ArrayList;
import java.util.HashMap;

import borge.web.teamspirit.client.SessionData;
import borge.web.teamspirit.client.TeamSpiritConstants;
import borge.web.teamspirit.client.data.Team;
import borge.web.teamspirit.client.data.TeamPlayer;
import borge.web.teamspirit.client.interfaces.DataProvider;
import borge.web.teamspirit.client.interfaces.PanelHandler;
import borge.web.teamspirit.client.interfaces.ServerCallbackHandler;
import borge.web.teamspirit.client.interfaces.PersistentData.DataKey;
import borge.web.teamspirit.client.interfaces.WidgetEventHandler.WidgetEventType;
import borge.web.teamspirit.client.page.PagePanel;
import borge.web.teamspirit.client.page.team.TokenData;
import borge.web.teamspirit.client.servercomm.DBQuery;
import borge.web.teamspirit.client.servercomm.DBQueryResults;
import borge.web.teamspirit.client.servercomm.ServerComm;
import borge.web.teamspirit.client.servercomm.DBQueryResults.Result;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.Panel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 * Implements PanelHandler to control the different panels
 * for the different purposes
 * @author Andreas Borglin
 */
public class TeamPagePanel extends PagePanel implements PanelHandler, ServerCallbackHandler {

	// Top root panel
	//private DockPanel iSuperPanel;
	
	// Top panel
	private TopPanel iTopPanel;
	private LeftPanel iLeftPanel;
	private Panel iCurCenterPanel;
	private RightPanel iRightPanel;
	
	private HashMap<String, MiddlePanel> iTokenMap;
	
	private static TeamSpiritConstants iConstants;
	
	private String iToken;
	private Team iTeam;
	
	static{
		iConstants = GWT.create(TeamSpiritConstants.class);
	}
	
	public static TeamSpiritConstants getConstants(){
		return iConstants;
	}
	
	public TeamPagePanel(){
		
		
	}
	
	private void initPanel(){
		
		if(getWidgetCount() == 0){
			iTopPanel = new TopPanel();
			iLeftPanel = new LeftPanel(this);
			iRightPanel = new RightPanel();

			setBorderWidth(2);

			add(iTopPanel, DockPanel.NORTH);
			add(iLeftPanel, DockPanel.WEST);
			//setCenterPanel(iWelcomePanel);
			add(iRightPanel, DockPanel.EAST);

			iTokenMap = new HashMap<String, MiddlePanel>();
		}
	}
	
	private void forwardToken(String aPanel, String aWidget, String aData){
		
		// Token = PanelKey?
		// Token = #Panel=2&Widget=4&Id=
		// www.bolltroll.com/index.html#Show/Serie/12

		MiddlePanel panel = iTokenMap.get(aPanel);
		
		if(panel == null){
			// create panek
			panel = createPanel(aPanel);
		}

		setCenterPanel(panel);
		panel.forwardToken(aWidget, aData);
			// forward toke
		
	}
	
	private MiddlePanel createPanel(String aPanel){
		
		// TODO: arrange in optimal order
		MiddlePanel panel = null;
		if(aPanel.equals(TokenData.CREATE) ||
				aPanel.equals(TokenData.EDIT)){
			panel = new CreateEditPanel(this);
		}
		else if(aPanel.equals(TokenData.LIST)){
			panel = new ListPanel(this);
		}
		else if(aPanel.equals(TokenData.SHOW)){
			panel = new ShowPanel(this);
		}
		else if(aPanel.equals(TokenData.SEARCH)){
			panel = new SearchPanel();
		}
		else if(aPanel.equals(TokenData.WELCOME)){
			panel = new WelcomePanel();
		}
		else
			Window.alert("Unknown panel token: " + aPanel);
		
		iTokenMap.put(aPanel, panel);
		return panel;
	}

	private void setCenterPanel(Panel aPanel){
		
		if(iCurCenterPanel != null)
			remove(iCurCenterPanel);
		add(aPanel, DockPanel.CENTER);
		iCurCenterPanel = aPanel;
		
	}
	
	
	public void switchPanel(WidgetEventType aWidgetEvent, DataProvider aDataProvider){
	        
	    iLeftPanel.handleWidgetEvent(WidgetEventType.CLEAR_MENU);
	    
	}


	@Override
	public void handleToken(String aToken) {

		// If we received token from parent,
		// get team and
		int teamEnd = aToken.indexOf(TokenData.TOKENIZER);
		if(teamEnd == -1)
			teamEnd = aToken.length();
		String team = aToken.substring(0, teamEnd);
		
		// TODO: this is messy..fix
		SessionData.sBaseToken = TokenData.TEAM_MODE + TokenData.TOKENIZER + team;
		
		if(teamEnd != aToken.length())
			iToken = aToken.substring(teamEnd + 1, aToken.length());
		else
			iToken = null;
		
		if(iTeam == null || !team.equals(iTeam.getName())){
			DBQuery query = new DBQuery(DataKey.TEAM, Team.class.getName());
			query.addFilter("iName", DBQuery.EQUALS, "teamName", "String", team, null);
			ServerComm.getObjectList(query, this);
		}
		else
			forwardToken();
	}
	
	public void forwardToken(){
		
		if(iToken == null){
			History.newItem(TokenData.assembleTeamToken(TokenData.WELCOME, ""));
			return;
		}
		
		int panelEnd = iToken.indexOf(TokenData.TOKENIZER);
		String panel = iToken.substring(0, panelEnd);
		
		int widgetEnd = iToken.indexOf(TokenData.TOKENIZER, panelEnd + 1);
		if(widgetEnd == -1)
			widgetEnd = iToken.length();
		
		String widget = iToken.substring(panelEnd + 1, widgetEnd);
		
		String data = null;
		
		if(widgetEnd != iToken.length()){
			data = iToken.substring(widgetEnd + 1, iToken.length());
		}
		
		forwardToken(panel, widget, data);
	}

	@Override
	public void handleServerCallback(DBQueryResults aResult, CallbackType aType) {
		// TODO Auto-generated method stub
		Result result = aResult.getResult(DataKey.TEAM);
		if(result != null && result.getResultList() != null){
			Team team = (Team)result.getResultList().get(0);
			iTeam = team;
			SessionData.sCurrentTeam = team;
			initPanel();
			forwardToken();
			
			// get players while user is considering what to click on :-)
			DBQuery query = new DBQuery(DataKey.TEAMPLAYER, TeamPlayer.class.getName());
			query.addFilter("iTeamKey", DBQuery.EQUALS, "teamKey", "String", iTeam.getEncodedKey(), null);
			ServerComm.getObjectList(query, this);
		}
		
		result = aResult.getResult(DataKey.TEAMPLAYER);
		if(result != null){
			SessionData.sCurrentTeam.setPlayers(result.getResultList());
		}
	}

	@Override
	public void handleServerError(Throwable t) {
		// TODO Auto-generated method stub
		Window.alert("teampagepanel error: " + t.toString());
	}


}
